import React, {
  useLayoutEffect,
  useReducer,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";

import ReactReduxContext from "../ReactReduxContext";
import shallowEqual from "./utils";

function useSelector(selector, equalityFn = shallowEqual) {
  const { store } = React.useContext(ReactReduxContext);

  // const state = store.getState();
  // const selectedState = selector(state);
  // 用于优化
  // const lastSelectedState = useRef(null);
  // const [, forceUpdate] = useReducer((x) => x + 1, 0);
  // useLayoutEffect(() => {
  //   store.subscribe(() => {
  //     // 比较老状态和新选中状态是否相等，如果相等，不刷新
  //     const selectedState = selector(store.getState());
  //     // if (selectedState !== lastSelectedState.current) {
  //     if (!equalityFn(lastSelectedState.current, selectedState)) {
  //       forceUpdate();
  //       lastSelectedState.current = selectedState;
  //       console.log("重新渲染");
  //     }
  //     // forceUpdate();
  //   });
  // }, []);
  // return selectedState;

  // react 18
  return useSyncExternalStore(store.subscribe, () =>
    selector(store.getState())
  );
}

function useSyncExternalStore1(subscribe, getSnapShot) {
  const [state, setState] = useState(getSnapShot());

  useLayoutEffect(() => {
    subscribe(() => {
      setState(getSnapShot());
    });
  }, []);

  return state;
}

export default useSelector;
